﻿using AutoMapper;
using B.S.XZYData.Api.Wrter.Application.Command.Permission;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Permission
{
    /// <summary>
    /// 权限删除实现层
    /// </summary>
    public class DeletePermissionHandler : IRequestHandler<DeletePermissionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DeletePermissionHandler> logger;

        public DeletePermissionHandler(IBaseRepository<PermissionModel> permissionRepo, IMapper mapper, ILogger<DeletePermissionHandler> logger)
        {
            this.permissionRepo = permissionRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 删除权限方法
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回查询到的权限列表</returns>
        public Task<ApiResult<int>> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = new ApiResult<int>();
                var permission = permissionRepo.GetValue(request.Id).Result;
                if (permission == null)
                {
                    res.Msg = "暂无数据!";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                permission.IsDeleted = true;
                int r = permissionRepo.UpdateAsync(permission).Result;
                if (r > 0)
                {
                    res.Data = r;
                    res.Msg = "删除权限成功!";
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Data = r;
                    res.Msg = "删除权限失败!";
                    res.Code = ApiEnum.Fail;
                }

                logger.LogInformation($"删除权限{permission.PermissionName}成功");
                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError("删除权限发生异常" + ex.Message);
                var res = new ApiResult<int>();
                res.Msg = "删除权限发生异常" + ex.Message;
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
                throw;
            }
        }
    }
}
